<template>
  <div class="image-upload-box">
    <!-- file-list: 用于图片回显
  limit: 限制图片上传个数
  on-remove: 移除图片时触发的属性 -->
    <el-upload
      :class="{ 'image-upload': fileList.length > 0 }"
      action="#"
      list-type="picture-card"
      :http-request="uploadFn"
      :file-list="fileList"
      :limit="1"
      :on-remove="removeFn"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <!-- 进度条
    需求：当上传图片的时候显示进度条，且上传完成后隐藏进度条-->
    <el-progress
      v-if="percent > 0 && percent < 100"
      type="circle"
      :width="100"
      :percentage="percent"
    />
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
var cos = new COS({
  SecretId: 'AKIDkJfngKirlPoxqTr1wd4GCsJUSBfutd7L',
  SecretKey: '1nLfngKirkNlwrY1EBtmPmumPm35rNde'
})
export default {
  data() {
    return {
      fileList: [],
      percent: 0 // 当前上传进度
    }
  },
  methods: {
    // 移除图片
    removeFn() {
      this.fileList = []
    },
    // 上传图片
    uploadFn(data) {
      this.fileList.push({
        url: ''
      })
      //   console.log(15, data)
      // 调用腾讯云提供的上传文件的方法，实现图片上传
      cos.putObject(
        {
          Bucket: 'wsh-rz-1313158334' /* 必须 -- 储存桶名字 */,
          Region: 'ap-guangzhou' /* 存储桶所在地域，必须字段 */,
          Key: Date.now().toString() /* 必须 -- 上传到腾讯云后的文件名 -- 字符串 */,
          StorageClass: 'STANDARD',
          Body: data.file, // 上传文件对象
          onProgress: (progressData) => {
            console.log('当前图片上传的进度：', progressData.percent)
            this.percent = +(progressData.percent * 100).toFixed(2)
          }
        },
        (err, data) => {
          // 当err值为null的时候，表示图片上传成功，否则失败
          if (!err) {
            this.fileList[0].url = 'http://' + data.Location
          }
        }
      )
    }
  }
}
</script>

<style lang="scss">
.image-upload-box {
  position: relative;
  display: inline-block;
  .el-progress {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -55%);
  }
}
.image-upload {
  .el-upload--picture-card {
    display: none;
  }
}
</style>
